<?php
/**
 * Created by PhpStorm.
 * User: wq
 * Date: 2021/5/6
 * Time: 15:03
 */

namespace App\Utils;

use App\Exceptions\ApiException;
use phpDocumentor\Reflection\Types\Self_;

/**
 * 常用工具类
 * Class Tools
 * @package App\Utils
 */
class Tools
{
    /**
     * @param $len
     * @return string
     * 生成随机字符串
     */
    public static function randStr($len)
    {
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; // characters to build the password from
        $string='';
        for(;$len>=1;$len--)
        {
            $position=rand()%strlen($chars);
            $string.=substr($chars,$position,1);
        }
        return $string;
    }

    /**
     * @param $len
     * @return string
     * 生成随机数字串
     */
    public static function randNumber($len)
    {
        $chars='0123456789'; // characters to build the password from
        $string='';
        for(;$len>=1;$len--)
        {
            $position=rand()%strlen($chars);
            $string.=substr($chars,$position,1);
        }
        return $string;
    }

    /**
     * 生成唯一字符串
     * @param $len
     * @return string
     */
    public static function getUuid()
    {
        $len = 8;
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; // characters to build the password from
        $string='';
        for(;$len>=1;$len--)
        {
            $position=rand()%strlen($chars);
            $string.=substr($chars,$position,1);
        }
        return time().$string;
    }

    /**
     * curl post json 请求
     * */
    public static function curlPost($url, $data = [], $aHeader = "")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ($aHeader) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

    /**
     * es获取分词
     * @param string $text
     * @return array
     * @throws ApiException
     */
    public static function getParticiple(string $text)
    {
        $host = "http://47.99.217.16:9202/_analyze";
        $data = [
            'text' => $text,
            'analyzer' => 'ik_max_word'
        ];
        $header = [
            'Content-Type: application/json'
        ];
        try {
            $re = self::curlPost($host, json_encode($data),$header);
            $data = json_decode($re[1], true);
            if ($data && isset($data['tokens'])) {
                $list = array_map(function ($v) {
                    return $v['token'];
                }, $data['tokens']);
            }
            //将分解的原值放入头部
            array_unshift($list,$text);
            return $list;
        } catch (\Exception $e) {
            throw new ApiException($e -> getMessage());
        }
    }

    public static function checkMobile($mobile)
    {
        $pattern = '/^1[34578]\d{9}$/';
        $r = preg_match($pattern,$mobile);
        return $r;
    }

    public static function checkEmil($mail)
    {
        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
        $r = preg_match($pattern, $mail);
        return $r;
    }

    /**
     * 检测是否有特殊字符
     * @param $str
     * @return bool
     */
    public static function checkSpecialChar($str)
    {
        $length = mb_strlen($str);
        $array = [];
        for ($i=0; $i<$length; $i++) {
            $array[] = mb_substr($str, $i, 1, 'utf-8');
            if( strlen($array[$i]) >= 4 ){
                return true;
            }
        }
        return false;
    }

    public static function getWholeUrl($url)
    {
        return env('APP_FILE_URL').$url;
    }

    /**
     * 生成海报兑换码
     */
    public static function getCheckCode($s_code,$code,$num)
    {
        $res = $s_code.sprintf('%04d',rand(0,9999)).array_rand(array_flip(range('A','Z'))).sprintf('%04d',rand(0,9999)).$code.$num;

        return $res;
    }

    public static function getNftHash($token,$content)
    {
        $priK = "-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCjJPCkJTe1lY8A
UxD/Y8MjJAC17Zj3+uGF4RerIRzy5n4Q62Nfye/jSMzXdcMeBijUjIWhR5ZFviUn
g6ct6F9zd0aHlad+191gxSTrxaVXQZD29Ueo3oN5LQDMdglpR8oV+i8EvjaGwj6b
WclLry3UapGC1+EujemEh/xf9pJ/Ou3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GBALjg
J6h9eMH0Uws3t7NP1TV2C+e5Bb+hDD1zLogavs4+2jxKmEiwCYS3+3FjEopd/VhC
EbanHg4fV3vP6olzeroXXmEAD5W94Wj7RIue51Wp+Qci559xZ/yq3DMybHrf9ABe
WOLmnJ3gkxrX2WRHxix/3Jod/i9oYr9jjNamIoChAoGBAKpljgnvbqhJ1Af2KW/8
8dsQpYhhLn4BVMtA3NIzzjz/CmzcbmATek6kVVVxf9q+EUZvV9dkUX4xpthickHu
E2hGTxyaDgJzPd2xjSC/Nr8g9jNRDxzv1TdkBy474FBSuVdF/nwBtp7JJxMU+yCJ
BCYiSUNmQf/IJO8ygoTiU6QK
-----END PRIVATE KEY-----
";
        $accessId = "6io5nkvKMXHAYHMM";
        $bizid = "a00e36c5";
        $res = self::saveCertificate($token,$bizid,$content,$accessId);
        $res = json_decode($res[1],true);
        if ($res['code'] != 200){
            $res = self::getNftHash($token,$content);
        }
        return $res;
    }

//    public static function getNftToken($secret,$time,$accessId)
//    {
//        $token = RedisUtils::getNftToken();
//        if ($token){
//            return $token;
//        }
//        $url = "https://rest.baas.alipay.com/api/contract/shakeHand";
//        $data['secret'] = $secret;
//        $data['time'] = $time;
//        $data['accessId'] = $accessId;
////        $header = array("Content-Type:application/json;charset:UTF-8");
//        $token = self::http_post_data($url,json_encode($data));
//        $data = json_decode($token[1],true);
//        RedisUtils::setNftToken($token['data']['data']);
//        return $token['data']['data'];
//
//
//    }

//    public static function RsaEncrypt($str,$pri_key){
//        $pi_key =openssl_pkey_get_private($pri_key);
//        if(!$pi_key)return false;//秘钥不可用
//        openssl_private_encrypt($str,$encrypted,$pi_key);
//        $encrypted =urlencode($encrypted);
//        return $encrypted;
//        openssl_sign($str,$sign,$pri_key,'sha256WithRSAEncryption');
//        return ($sign);
//    }
    public static function saveCertificate($token,$bizid,$content,$accessId)
    {
        $data['token'] = $token;
        $data['bizid'] = $bizid;
        $data['orderId'] = 'order_'.self::randStr(16);
        $data['account'] = 'xmsh';
        $data['content'] = $content;
        $data['mykmsKeyId'] = 'eNUxV81MMXHAYHMM1640052535492';
        $data['method'] = 'DEPOSIT';
        $data['accessId'] = $accessId;
        $data['gas'] = 100000;
        $data['tenantid']= "MXHAYHMM";
        $url = "https://rest.baas.alipay.com/api/contract/chainCallForBiz";
        $res = self::curlPost($url,json_encode($data),array('Content-Type: application/json; charset=utf-8'));
        return $res;
    }


}
